package service

import (
	"wit-admin-go/system/app/dto"
	"wit-admin-go/system/utils"
)

type casbinService struct{}

var CasbinService = new(casbinService)

// CasbinRolesBindUser 用户绑定角色
func (u *casbinService) CasbinRolesBindUser(userId string, roleId string) error {
	//if len(roleId) != 0 {
	//	for _, item := range roleId {
	//		_, _ = utils.WitEnforcer.AddRoleForUser(userId, item)
	//	}
	//}
	_, err := utils.WitEnforcer.AddRoleForUser(userId, roleId)
	return err
}

// PutCasbinRolesBindUser 修改用户角色
func (u *casbinService) PutCasbinRolesBindUser(userId string, roleId string) error {
	user := new(dto.UpdateUser)
	user.Id = userId
	user.RoleId = roleId
	err := UserService.PutUpdateUser(*user)
	if err != nil {
		return err
	}
	_, _ = utils.WitEnforcer.DeleteRolesForUser(userId)
	_, err = utils.WitEnforcer.AddRoleForUser(userId, roleId)
	if err != nil {
		return err
	}
	return nil
}

// DeleteCasbinRolesBindUser 删除用户角色
func (u *casbinService) DeleteCasbinRolesBindUser(userId string) error {
	user, _ := UserService.GetUserById(userId)
	user.RoleId = "null"
	err := utils.DB.Model(&user).Updates(user).Where("id = ?", user.Id).Error
	if err != nil {
		return err
	}
	_, _ = utils.WitEnforcer.DeleteRolesForUser(userId)
	return nil
}
